<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;

class OrderRequestRateLimit
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $userId = \Auth::guard('api')->user() ? \Auth::guard('api')->user()->id : null;

        // 检查缓存中是否存在用户最后一次请求的时间戳
        $lastRequestTime = Cache::get('user_request_time_' . $userId);

        // 如果上次请求时间存在且距今不足30秒，则拒绝请求
        if ($lastRequestTime && now()->diffInSeconds($lastRequestTime) < 30) {
            return response()->json(['success' => false, 'code' => 200, 'message' => '操作太快啦', 'timestamp' => Carbon::now()->timestamp]);
        }

        // 否则，更新用户的最后请求时间并继续请求
        Cache::put('user_request_time_' . $userId, now(), 30);
        return $next($request);
    }
}
